package com.dapangdong.testdemo.controller.test;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author : yhd
 * @program: gulimall
 * @since : 2023-04-10 09:55
 */
@RequiredArgsConstructor
@Slf4j
@Api(tags = "延迟任务")
@RestController
@RequestMapping(value = "/timer")
public class TimerController {

    @ApiOperation(value = "Timer")
    @GetMapping("/test")
    public Object test(){
        Timer timer = new Timer();

        log.info("提交延迟任务");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("执行延迟任务");
            }
        }, 5000);
        System.out.println("运行结束");

        return "请求成功："+ LocalDateTime.now();
    }

    /**
     * ScheduledThreadPoolExecutor继承了ThreadPoolExecutor，也就是继承了线程池，所以可以有很多个线程来执行任务。
     *
     * ScheduledThreadPoolExecutor在构造的时候会传入一个DelayedWorkQueue阻塞队列，所以线程池内部的阻塞队列是DelayedWorkQueue
     * @return
     */
    @ApiOperation(value = "ScheduledThreadPoolExecutor")
    @GetMapping("/scheduledThreadPoolExecutor")
    public Object scheduledThreadPoolExecutor(){
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2, new ThreadPoolExecutor.CallerRunsPolicy());

        System.out.println("提交延迟任务");
        executor.schedule(() -> log.info("执行延迟任务"), 5, TimeUnit.SECONDS);

        return "请求成功："+ LocalDateTime.now();
    }




}
